/*
 * Tencent is pleased to support the open source community by making ovCompose available.
 * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tencent.compose.sample.test

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Button
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow

/**
 * 测试服务类
 */
class TestService {
    
    /**
     * 模拟用户登录
     */
    suspend fun loginUser(email: String, password: String): TestUser? {
        delay(1000) // 模拟网络延迟
        return if (TestUtils.isValidEmail(email)) {
            TestDataGenerator.generateTestUser()
        } else null
    }
    
    /**
     * 模拟获取用户列表
     */
    suspend fun getUsers(): List<TestUser> {
        delay(500)
        return (1..10).map { TestDataGenerator.generateTestUser(it.toLong()) }
    }
    
    /**
     * 模拟获取商品列表
     */
    suspend fun getProducts(): List<TestProduct> {
        delay(800)
        return (1..15).map { TestDataGenerator.generateTestProduct(it.toString()) }
    }
    
    /**
     * 模拟创建订单
     */
    suspend fun createOrder(userId: Long, items: List<OrderItem>): TestOrder? {
        delay(1200)
        return TestDataGenerator.generateTestOrder().copy(
            userId = userId,
            items = items,
            totalAmount = items.sumOf { it.totalPrice }
        )
    }
    
    /**
     * 模拟发送消息
     */
    suspend fun sendMessage(senderId: Long, receiverId: Long, content: String): TestMessage? {
        delay(300)
        return TestDataGenerator.generateTestMessage().copy(
            senderId = senderId,
            receiverId = receiverId,
            content = content
        )
    }
    
    /**
     * 模拟创建事件
     */
    suspend fun createEvent(title: String, description: String, organizer: String): TestEvent? {
        delay(600)
        return TestDataGenerator.generateTestEvent().copy(
            title = title,
            description = description,
            organizer = organizer
        )
    }
    
    /**
     * 模拟搜索功能
     */
    suspend fun searchUsers(query: String): List<TestUser> {
        delay(400)
        val allUsers = getUsers()
        return allUsers.filter { 
            it.name.contains(query, ignoreCase = true) || 
            it.email.contains(query, ignoreCase = true) 
        }
    }
    
    /**
     * 模拟搜索商品
     */
    suspend fun searchProducts(query: String): List<TestProduct> {
        delay(500)
        val allProducts = getProducts()
        return allProducts.filter { 
            it.name.contains(query, ignoreCase = true) || 
            it.description.contains(query, ignoreCase = true) 
        }
    }
    
    /**
     * 模拟获取统计数据
     */
    suspend fun getStatistics(): TestStatistics {
        delay(800)
        return TestDataGenerator.generateTestStatistics()
    }
    
    /**
     * 模拟文件上传
     */
    suspend fun uploadFile(fileName: String, fileSize: Long, progressCallback: (Int) -> Unit): Boolean {
        return TestUtils.simulateFileUpload(fileSize, progressCallback)
    }
    
    /**
     * 模拟数据下载
     */
    suspend fun downloadData(dataSize: Long, progressCallback: (Int) -> Unit): ByteArray {
        return TestUtils.simulateDataDownload(dataSize, progressCallback)
    }
}

/**
 * 测试仓库类
 */
class TestRepository {
    private val testService = TestService()
    private val cachedUsers = mutableListOf<TestUser>()
    private val cachedProducts = mutableListOf<TestProduct>()
    private val cachedOrders = mutableListOf<TestOrder>()
    
    /**
     * 获取用户列表（带缓存）
     */
    suspend fun getUsers(forceRefresh: Boolean = false): List<TestUser> {
        return if (cachedUsers.isEmpty() || forceRefresh) {
            val users = testService.getUsers()
            cachedUsers.clear()
            cachedUsers.addAll(users)
            users
        } else {
            cachedUsers.toList()
        }
    }
    
    /**
     * 获取商品列表（带缓存）
     */
    suspend fun getProducts(forceRefresh: Boolean = false): List<TestProduct> {
        return if (cachedProducts.isEmpty() || forceRefresh) {
            val products = testService.getProducts()
            cachedProducts.clear()
            cachedProducts.addAll(products)
            products
        } else {
            cachedProducts.toList()
        }
    }
    
    /**
     * 创建订单
     */
    suspend fun createOrder(userId: Long, items: List<OrderItem>): TestOrder? {
        val order = testService.createOrder(userId, items)
        order?.let { cachedOrders.add(it) }
        return order
    }
    
    /**
     * 获取订单列表
     */
    suspend fun getOrders(): List<TestOrder> {
        return cachedOrders.toList()
    }
    
    /**
     * 搜索用户
     */
    suspend fun searchUsers(query: String): List<TestUser> {
        return testService.searchUsers(query)
    }
    
    /**
     * 搜索商品
     */
    suspend fun searchProducts(query: String): List<TestProduct> {
        return testService.searchProducts(query)
    }
    
    /**
     * 获取统计数据
     */
    suspend fun getStatistics(): TestStatistics {
        return testService.getStatistics()
    }
    
    /**
     * 清除缓存
     */
    fun clearCache() {
        cachedUsers.clear()
        cachedProducts.clear()
        cachedOrders.clear()
    }
}

/**
 * 测试视图模型
 */
class TestViewModel {
    private val repository = TestRepository()
    
    var users by mutableStateOf<List<TestUser>>(emptyList())
        private set
    
    var products by mutableStateOf<List<TestProduct>>(emptyList())
        private set
    
    var orders by mutableStateOf<List<TestOrder>>(emptyList())
        private set
    
    var isLoading by mutableStateOf(false)
        private set
    
    var errorMessage by mutableStateOf<String?>(null)
        private set
    
    /**
     * 加载用户数据
     */
    suspend fun loadUsers() {
        isLoading = true
        errorMessage = null
        try {
            users = repository.getUsers()
        } catch (e: Exception) {
            errorMessage = "加载用户失败: ${e.message}"
        } finally {
            isLoading = false
        }
    }
    
    /**
     * 加载商品数据
     */
    suspend fun loadProducts() {
        isLoading = true
        errorMessage = null
        try {
            products = repository.getProducts()
        } catch (e: Exception) {
            errorMessage = "加载商品失败: ${e.message}"
        } finally {
            isLoading = false
        }
    }
    
    /**
     * 加载订单数据
     */
    suspend fun loadOrders() {
        isLoading = true
        errorMessage = null
        try {
            orders = repository.getOrders()
        } catch (e: Exception) {
            errorMessage = "加载订单失败: ${e.message}"
        } finally {
            isLoading = false
        }
    }
    
    /**
     * 搜索用户
     */
    suspend fun searchUsers(query: String) {
        isLoading = true
        errorMessage = null
        try {
            users = repository.searchUsers(query)
        } catch (e: Exception) {
            errorMessage = "搜索用户失败: ${e.message}"
        } finally {
            isLoading = false
        }
    }
    
    /**
     * 搜索商品
     */
    suspend fun searchProducts(query: String) {
        isLoading = true
        errorMessage = null
        try {
            products = repository.searchProducts(query)
        } catch (e: Exception) {
            errorMessage = "搜索商品失败: ${e.message}"
        } finally {
            isLoading = false
        }
    }
    
    /**
     * 创建订单
     */
    suspend fun createOrder(userId: Long, items: List<OrderItem>) {
        isLoading = true
        errorMessage = null
        try {
            val order = repository.createOrder(userId, items)
            if (order != null) {
                orders = orders + order
            }
        } catch (e: Exception) {
            errorMessage = "创建订单失败: ${e.message}"
        } finally {
            isLoading = false
        }
    }
    
    /**
     * 刷新数据
     */
    suspend fun refreshData() {
        isLoading = true
        errorMessage = null
        try {
            users = repository.getUsers(forceRefresh = true)
            products = repository.getProducts(forceRefresh = true)
            orders = repository.getOrders()
        } catch (e: Exception) {
            errorMessage = "刷新数据失败: ${e.message}"
        } finally {
            isLoading = false
        }
    }
    
    /**
     * 清除错误
     */
    fun clearError() {
        errorMessage = null
    }
}

/**
 * 测试页面
 */
@Composable
fun TestServicePage() {
    val viewModel = remember { TestViewModel() }
    var currentTab by remember { mutableStateOf(0) }
    var searchQuery by remember { mutableStateOf("") }
    
    LaunchedEffect(Unit) {
        viewModel.loadUsers()
        viewModel.loadProducts()
        viewModel.loadOrders()
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("测试服务") }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // 标签页
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                listOf("用户", "商品", "订单").forEachIndexed { index, title ->
                    Button(
                        onClick = { currentTab = index },
                        modifier = Modifier.weight(1f)
                    ) {
                        Text(title)
                    }
                }
            }
            
            // 搜索和操作按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Button(
                    onClick = {
                        when (currentTab) {
                            0 -> viewModel.searchUsers(searchQuery)
                            1 -> viewModel.searchProducts(searchQuery)
                        }
                    }
                ) {
                    Text("搜索")
                }
                
                Button(
                    onClick = { viewModel.refreshData() }
                ) {
                    Text("刷新")
                }
            }
            
            // 错误信息
            viewModel.errorMessage?.let { error ->
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    backgroundColor = MaterialTheme.colors.error.copy(alpha = 0.1f)
                ) {
                    Text(
                        text = error,
                        modifier = Modifier.padding(16.dp),
                        color = MaterialTheme.colors.error
                    )
                }
            }
            
            // 加载状态
            if (viewModel.isLoading) {
                Text(
                    text = "正在加载...",
                    fontSize = 16.sp,
                    color = MaterialTheme.colors.primary
                )
            }
            
            // 内容区域
            when (currentTab) {
                0 -> {
                    if (viewModel.users.isNotEmpty()) {
                        LazyColumn(
                            verticalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            items(viewModel.users) { user ->
                                Card(
                                    modifier = Modifier.fillMaxWidth(),
                                    elevation = 2.dp
                                ) {
                                    Column(
                                        modifier = Modifier.padding(16.dp)
                                    ) {
                                        Text(
                                            text = user.name,
                                            fontSize = 16.sp,
                                            fontWeight = FontWeight.Medium
                                        )
                                        Text(
                                            text = user.email,
                                            fontSize = 14.sp,
                                            color = MaterialTheme.colors.onSurface.copy(alpha = 0.7f)
                                        )
                                        Text(
                                            text = "年龄: ${user.age}",
                                            fontSize = 12.sp,
                                            color = MaterialTheme.colors.onSurface.copy(alpha = 0.6f)
                                        )
                                    }
                                }
                            }
                        }
                    } else {
                        Text("暂无用户数据")
                    }
                }
                
                1 -> {
                    if (viewModel.products.isNotEmpty()) {
                        LazyColumn(
                            verticalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            items(viewModel.products) { product ->
                                Card(
                                    modifier = Modifier.fillMaxWidth(),
                                    elevation = 2.dp
                                ) {
                                    Column(
                                        modifier = Modifier.padding(16.dp)
                                    ) {
                                        Text(
                                            text = product.name,
                                            fontSize = 16.sp,
                                            fontWeight = FontWeight.Medium
                                        )
                                        Text(
                                            text = product.description,
                                            fontSize = 14.sp,
                                            color = MaterialTheme.colors.onSurface.copy(alpha = 0.7f)
                                        )
                                        Text(
                                            text = "价格: ${TestUtils.formatPrice(product.price)}",
                                            fontSize = 14.sp,
                                            fontWeight = FontWeight.Medium,
                                            color = MaterialTheme.colors.primary
                                        )
                                    }
                                }
                            }
                        }
                    } else {
                        Text("暂无商品数据")
                    }
                }
                
                2 -> {
                    if (viewModel.orders.isNotEmpty()) {
                        LazyColumn(
                            verticalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            items(viewModel.orders) { order ->
                                Card(
                                    modifier = Modifier.fillMaxWidth(),
                                    elevation = 2.dp
                                ) {
                                    Column(
                                        modifier = Modifier.padding(16.dp)
                                    ) {
                                        Text(
                                            text = "订单 #${order.id}",
                                            fontSize = 16.sp,
                                            fontWeight = FontWeight.Medium
                                        )
                                        Text(
                                            text = "状态: ${order.status.displayName}",
                                            fontSize = 14.sp,
                                            color = MaterialTheme.colors.onSurface.copy(alpha = 0.7f)
                                        )
                                        Text(
                                            text = "总金额: ${TestUtils.formatPrice(order.totalAmount)}",
                                            fontSize = 14.sp,
                                            fontWeight = FontWeight.Medium,
                                            color = MaterialTheme.colors.primary
                                        )
                                    }
                                }
                            }
                        }
                    } else {
                        Text("暂无订单数据")
                    }
                }
            }
        }
    }
}
